package com.internetCafes.spms.web.tenant.controller;

import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.common.utils.entity.RR;
import com.internetCafes.spms.core.annotation.SysLog;
import com.internetCafes.spms.core.model.pageModel.DataGrid;
import com.internetCafes.spms.core.utils.Query;
import com.internetCafes.spms.core.utils.R;
import com.internetCafes.spms.web.certificate.entity.EmployeeInfo;
import com.internetCafes.spms.web.certificate.service.EmployeeInfoService;
import com.internetCafes.spms.web.tenant.bizservice.TenantDeptBizService;
import com.internetCafes.spms.web.tenant.model.TenantDeptInfo;
import com.internetCafes.spms.web.tenant.model.TenantInfo;
import com.internetCafes.spms.web.tenant.service.TenantDeptInfoService;
import com.internetCafes.spms.web.tenant.service.TenantInfoService;
import com.internetCafes.spms.web.tenant.vo.TenantDeptInfoVo;
import com.sms.common.util.hutool.core.collection.CollectionUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 租户组织架构
 *
 * @author Sunny
 * @email rekeeper2011@hotmail.com
 * @date 2019-10-31 18:09:54
 */
@RestController
@RequestMapping("/tenant/tenantDeptInfo")
public class TenantDeptInfoController {

    @Autowired
    private TenantDeptInfoService tenantDeptInfoService;

    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private EmployeeInfoService employeeInfoService;

    @Autowired
    private TenantDeptBizService deptBizService;

    /**
     * 修改 - 企业部门结构信息
     */
    @SysLog("全量修改 - 企业部门结构信息")
    @PutMapping("/batch/tree")
    @RequiresPermissions("tenant:tenantDeptInfo:update")
    public RR<Void> updateBatchByTree(@RequestBody TenantDeptInfoVo req) {
        return deptBizService.updateBatchByTree(req) ? RR.success() : RR.fail();
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("tenant:tenantDeptInfo:list")
    public R list(@RequestParam Map<String, Object> params) {

        //查询列表数据
        Query query = new Query(params);
        params = new HashMap<>();

        DataGrid dataGrid = tenantDeptInfoService.dataGrid(params, query.getPage(), query.getLimit());

        return R.ok().put("page", dataGrid);
    }


    /**
     * 列表
     */
    @RequestMapping("/tree")
    public R tree(Long tenantId, Integer filterFlag) {
        /*if (tenantId == null) {
            tenantId = ShiroUtils.getUserEntity().getDeptId();
        }

        TenantInfo t = tenantInfoService.findById(tenantId);
        TenantDeptInfoVo _vo = null;
        if (t != null) {
            TenantDeptInfoVo vo = new TenantDeptInfoVo(0L, t.getTenantName(), 0L, "");
            vo.setCertificateCount(0L);
            vo.setDisabled(true);
            Map<String, Object> params = new HashMap<>();
            params.put("tenantId", tenantId);
            params.put("parentId", 0L);
            List<TenantDeptInfoVo> tenantDeptInfoList = tenantDeptInfoService.selectByParamsUnionTenant(params);
            if (tenantDeptInfoList != null && tenantDeptInfoList.size() > 0) {
                tenantDeptInfoList.forEach(d -> {
                    d.setParentId(0L);
                    d.setParentName(t.getTenantName());
                    getDeptTree(t.getTenantId(), vo, d);
                });
            }
            _vo = vo;
        }*/
        TenantDeptInfoVo res = tenantDeptInfoService.tree(tenantId, filterFlag);
        return R.ok().put("deptInfo", res);
    }


    private void getDeptTree(Long tenantId, TenantDeptInfoVo vo, TenantDeptInfoVo d) {
        TenantDeptInfoVo _vo = new TenantDeptInfoVo(d.getId(), d.getDeptName(), d.getParentId(), d.getParentName());
        if (vo.getCertificateCount() == null) {
            vo.setCertificateCount(0L);
        }


        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("parentId", d.getId());
        List<TenantDeptInfoVo> tenantDeptInfoList = tenantDeptInfoService.selectByParamsUnionTenant(params);

        if (tenantDeptInfoList != null && tenantDeptInfoList.size() > 0) {
            for (TenantDeptInfoVo tenantDeptInfoVo : tenantDeptInfoList) {
                getDeptTree(tenantId, _vo, tenantDeptInfoVo);
                d.setCertificateCount(tenantDeptInfoVo.getCertificateCount() + d.getCertificateCount());
            }
        }
        _vo.setCertificateCount(vo.getCertificateCount() + d.getCertificateCount());
        vo.getChildren().add(_vo);
    }


    /**
     * 根据ID获取数据
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("tenant:tenantDeptInfo:info")
    public R info(@PathVariable("id") Long id) {
        TenantDeptInfo tenantDeptInfo = tenantDeptInfoService.findById(id);
        return R.ok().put("tenantDeptInfo", tenantDeptInfo);
    }


    /**
     * 保存
     */
    @SysLog("保存租户部门信息")
    @RequestMapping("/save")
    @RequiresPermissions("tenant:tenantDeptInfo:save")
    public R save(@RequestBody TenantDeptInfo tenantDeptInfo) {
        tenantDeptInfo.setCreateTime(new Date());
        if (tenantDeptInfo.getTenantId() != null) {
            tenantDeptInfo.setTenantId(ShiroUtils.getUserEntity().getDeptId());
        }
        Map<String, Object> params = new HashMap<>();
        params.put("deptName", tenantDeptInfo.getDeptName());
        params.put("parentId", tenantDeptInfo.getParentId());
        long count = tenantDeptInfoService.count(params);
        if (count > 0) {
            return R.error("该部门已存在");
        }
        tenantDeptInfo.setStatus(CommonConstants.CommonStatus.ENABLE);
        tenantDeptInfoService.save(tenantDeptInfo);
        return R.ok();
    }


    /**
     * 修改
     */
    @SysLog("修改租户部门信息")
    @RequestMapping("/update")
    @RequiresPermissions("tenant:tenantDeptInfo:update")
    public R update(@RequestBody TenantDeptInfo tenantDeptInfo) {
        TenantDeptInfo t = tenantDeptInfoService.findById(tenantDeptInfo.getId());
        if (t != null) {
            tenantDeptInfo.setTenantId(t.getTenantId());
            tenantDeptInfo.setCreateTime(t.getCreateTime());
            tenantDeptInfo.setType(t.getType());
            tenantDeptInfo.setStatus(t.getStatus());
            tenantDeptInfoService.update(tenantDeptInfo);
        }
        return R.ok();
    }


    /**
     * 删除
     */
    @SysLog("删除租户部门信息")
    @RequestMapping("/delete")
    @RequiresPermissions("tenant:tenantDeptInfo:delete")
    public R delete(Long id) {
        Map<String, Object> params = new HashMap<>();
        TenantDeptInfo t = tenantDeptInfoService.findById(id);
        params.put("deptId", id);
        params.put("tenantId", t.getTenantId());
        params.put("status", CommonConstants.CommonStatus.ENABLE);
        List<EmployeeInfo> employeeInfoList = employeeInfoService.query(params);
        if (CollectionUtil.isNotEmpty(employeeInfoList)) {
            return R.error("部门下有人员，不能删除");
        } else {
            tenantDeptInfoService.delete(id);
        }

        return R.ok();
    }

    /**
     * 列表
     */
    @RequestMapping("/listAll")
    @RequiresPermissions("tenant:tenantDeptInfo:list")
    public R listAll(Long tenantId) {
        if (tenantId == null) {
            tenantId = ShiroUtils.getUserEntity().getDeptId();
        }

        TenantInfo t = tenantInfoService.findById(tenantId);
        TenantDeptInfoVo vo = null;
        if (t != null) {
            vo = new TenantDeptInfoVo(0L, t.getTenantName(), 0L, "");
            vo.setDisabled(true);
            Map<String, Object> params = new HashMap<>();
            params.put("tenantId", tenantId);
            params.put("parentId", 0L);
        }
        List<TenantDeptInfo> data = tenantDeptInfoService.query(new HashMap<>());
        data.add(vo);

        return R.ok().put("data", data);
    }

    @GetMapping("/empCertiList")
    @RequiresPermissions("tenant:tenantDeptInfo:list")
    public R listEmpCerti() {
        Map<String, Object> params;
        List<TenantDeptInfoVo> children = tenantDeptInfoService.selectByParamsUnionCertificate();
        for (TenantDeptInfoVo tenantDeptInfoVo : children) {
            params = new HashMap<>();
            params.put("deptId", tenantDeptInfoVo.getId());
            params.put("status", 1);
            params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
            long employeeCount = employeeInfoService.count(params);
            tenantDeptInfoVo.setEmployeeCount(employeeCount);
            if (employeeCount == 0) {
                tenantDeptInfoVo.setKeepRate("0");
            } else {
                tenantDeptInfoVo.setKeepRate(String.format("%.3f", (double) tenantDeptInfoVo.getEmployeeWithCerti() / employeeCount));
            }
            tenantDeptInfoVo.setEmployeeCount(employeeCount);
            tenantDeptInfoVo.setEmployeeWithCerti(tenantDeptInfoVo.getEmployeeWithCerti());
        }
        CollectionUtil.sort(children, (o1, o2) -> (int) (o2.getCertificateCount() - o1.getCertificateCount()));
        return R.ok().put("data", children);
    }

    @GetMapping("/deptEmpList")
    @RequiresPermissions("tenant:tenantDeptInfo:list")
    public R listdeptEmp(TenantDeptInfoVo tenantDeptInfoVo) {
        List<TenantDeptInfoVo> deptList = tenantDeptInfoService.getChildren(tenantDeptInfoVo.getId(), new ArrayList<>());
        Map<String, Object> params = new HashMap<>();
        params.put("deptId", tenantDeptInfoVo.getId());
        if (tenantDeptInfoVo.getNameOrPost() != null) {
            params.put("nameOrPost", tenantDeptInfoVo.getNameOrPost());
        }
        params.put("status", CommonConstants.CommonStatus.ENABLE);
        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        List<EmployeeInfo> employeeList = employeeInfoService.query(params);
        return R.ok().put("deptList", deptList).put("employeeList", employeeList);
    }

}
